/**
 * 蓝牙设备选择弹窗组件
 * 
 * 用途：显示已配对的蓝牙设备列表，让用户选择要连接的NeuroSky设备
 * 方法：使用Jetpack Compose构建弹窗界面，集成BluetoothManager获取设备列表
 * 原理：通过Dialog组件展示设备列表，支持设备扫描和选择连接
 */
package com.example.brain_wave.ui.components

import android.bluetooth.BluetoothDevice
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bluetooth
import androidx.compose.material.icons.filled.BluetoothSearching
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.example.brain_wave.bluetooth.BluetoothManager
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import com.example.brain_wave.ui.theme.*

/**
 * 蓝牙设备选择弹窗
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BluetoothDeviceSelectionDialog(
    isVisible: Boolean,
    onDismiss: () -> Unit,
    onDeviceSelected: (BluetoothDevice) -> Unit,
    modifier: Modifier = Modifier
) {
    if (!isVisible) return
    
    val context = LocalContext.current
    val bluetoothManager = remember { BluetoothManager.getInstance(context) }
    var isScanning by remember { mutableStateOf(false) }
    var isLoading by remember { mutableStateOf(false) }
    var availableDevices by remember { mutableStateOf(listOf<BluetoothDevice>()) }
    var pairedDevices by remember { mutableStateOf<List<BluetoothDevice>>(emptyList()) }
    var neuroSkyDevices by remember { mutableStateOf<List<BluetoothDevice>>(emptyList()) }
    val scope = rememberCoroutineScope()
    
    // 加载已配对设备
    LaunchedEffect(isVisible) {
        if (isVisible) {
            isLoading = true
            try {
                val paired = bluetoothManager.getPairedDevices()
                pairedDevices = paired
                
                // 筛选NeuroSky设备
                val neuroSky = bluetoothManager.findNeuroSkyDevices()
                neuroSkyDevices = neuroSky
                
                println("📱 已配对设备数量: ${paired.size}")
                println("🧠 NeuroSky设备数量: ${neuroSky.size}")
                neuroSky.forEach { device ->
                    println("   - ${device.name} (${device.address})")
                }
            } catch (e: Exception) {
                println("❌ 获取设备列表失败: ${e.message}")
            } finally {
                isLoading = false
            }
        }
    }
    
    Dialog(
        onDismissRequest = onDismiss,
        properties = DialogProperties(
            dismissOnBackPress = true,
            dismissOnClickOutside = true,
            usePlatformDefaultWidth = false
        )
    ) {
        Card(
            modifier = modifier
                .fillMaxWidth(0.9f)
                .fillMaxHeight(0.7f)
                .shadow(
                    elevation = 16.dp,
                    shape = RoundedCornerShape(16.dp),
                    ambientColor = TechBlue
                ),
            shape = RoundedCornerShape(16.dp),
            colors = CardDefaults.cardColors(
                containerColor = TechSurface
            ),
            border = BorderStroke(1.dp, TechBorder)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(20.dp)
            ) {
                // 标题栏
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Bluetooth,
                            contentDescription = null,
                            tint = TechBlue,
                            modifier = Modifier.size(24.dp)
                        )
                        Text(
                            text = "选择蓝牙设备",
                            style = MaterialTheme.typography.headlineSmall,
                            color = TechTextPrimary,
                            fontWeight = FontWeight.Bold
                        )
                    }
                    
                    IconButton(
                        onClick = onDismiss,
                        colors = IconButtonDefaults.iconButtonColors(
                            contentColor = TechTextSecondary
                        )
                    ) {
                        Icon(
                            imageVector = Icons.Default.Close,
                            contentDescription = "关闭"
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 操作按钮
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    OutlinedButton(
                        onClick = {
                            isScanning = true
                            bluetoothManager.startScanning()
                            // 模拟扫描过程
                            scope.launch {
                                delay(3000)
                                isScanning = false
                                bluetoothManager.stopScanning()
                            }
                        },
                        enabled = !isScanning && !isLoading,
                        colors = ButtonDefaults.outlinedButtonColors(
                            contentColor = TechBlue
                        ),
                        border = BorderStroke(1.dp, TechBlue),
                        modifier = Modifier.weight(1f)
                    ) {
                        if (isScanning) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(16.dp),
                                strokeWidth = 2.dp,
                                color = TechBlue
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text("扫描中...")
                        } else {
                            Icon(
                                imageVector = Icons.Default.BluetoothSearching,
                                contentDescription = null,
                                modifier = Modifier.size(16.dp)
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text("扫描设备")
                        }
                    }
                    
                    OutlinedButton(
                        onClick = {
                            isLoading = true
                            try {
                                val paired = bluetoothManager.getPairedDevices()
                                pairedDevices = paired
                                val neuroSky = bluetoothManager.findNeuroSkyDevices()
                                neuroSkyDevices = neuroSky
                            } catch (e: Exception) {
                                println("❌ 刷新设备列表失败: ${e.message}")
                            } finally {
                                isLoading = false
                            }
                        },
                        enabled = !isLoading && !isScanning,
                        colors = ButtonDefaults.outlinedButtonColors(
                            contentColor = TechTextSecondary
                        ),
                        border = BorderStroke(1.dp, TechBorder)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Refresh,
                            contentDescription = null,
                            modifier = Modifier.size(16.dp)
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 设备列表
                if (isLoading) {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            CircularProgressIndicator(
                                color = TechBlue,
                                strokeWidth = 3.dp
                            )
                            Text(
                                text = "正在加载设备列表...",
                                color = TechTextSecondary,
                                style = MaterialTheme.typography.bodyMedium
                            )
                        }
                    }
                } else {
                    Column {
                        // NeuroSky设备部分
                        if (neuroSkyDevices.isNotEmpty()) {
                            Text(
                                text = "NeuroSky设备 (${neuroSkyDevices.size})",
                                style = MaterialTheme.typography.titleMedium,
                                color = TechTextPrimary,
                                fontWeight = FontWeight.SemiBold,
                                modifier = Modifier.padding(bottom = 8.dp)
                            )
                            
                            LazyColumn(
                                modifier = Modifier.weight(1f),
                                verticalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                items(neuroSkyDevices) { device ->
                                    DeviceItem(
                                        device = device,
                                        isNeuroSky = true,
                                        onClick = { onDeviceSelected(device) }
                                    )
                                }
                            }
                        }
                        
                        // 其他已配对设备部分
                        val otherDevices = pairedDevices.filter { device ->
                            !neuroSkyDevices.contains(device)
                        }
                        
                        if (otherDevices.isNotEmpty()) {
                            if (neuroSkyDevices.isNotEmpty()) {
                                Spacer(modifier = Modifier.height(16.dp))
                                Divider(color = TechBorder)
                                Spacer(modifier = Modifier.height(16.dp))
                            }
                            
                            Text(
                                text = "其他已配对设备 (${otherDevices.size})",
                                style = MaterialTheme.typography.titleMedium,
                                color = TechTextSecondary,
                                fontWeight = FontWeight.SemiBold,
                                modifier = Modifier.padding(bottom = 8.dp)
                            )
                            
                            LazyColumn(
                                modifier = Modifier.weight(1f),
                                verticalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                items(otherDevices) { device ->
                                    DeviceItem(
                                        device = device,
                                        isNeuroSky = false,
                                        onClick = { onDeviceSelected(device) }
                                    )
                                }
                            }
                        }
                        
                        // 无设备提示
                        if (pairedDevices.isEmpty()) {
                            Box(
                                modifier = Modifier.fillMaxSize(),
                                contentAlignment = Alignment.Center
                            ) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally,
                                    verticalArrangement = Arrangement.spacedBy(8.dp)
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.Bluetooth,
                                        contentDescription = null,
                                        tint = TechTextSecondary,
                                        modifier = Modifier.size(48.dp)
                                    )
                                    Text(
                                        text = "未找到已配对的设备",
                                        color = TechTextSecondary,
                                        style = MaterialTheme.typography.bodyLarge,
                                        textAlign = TextAlign.Center
                                    )
                                    Text(
                                        text = "请先在系统设置中配对NeuroSky设备",
                                        color = TechTextSecondary,
                                        style = MaterialTheme.typography.bodyMedium,
                                        textAlign = TextAlign.Center
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

/**
 * 设备列表项组件
 */
@Composable
private fun DeviceItem(
    device: BluetoothDevice,
    isNeuroSky: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .clickable { onClick() }
            .shadow(
                elevation = 2.dp,
                shape = RoundedCornerShape(8.dp),
                ambientColor = if (isNeuroSky) TechBlue else Color.Gray
            ),
        shape = RoundedCornerShape(8.dp),
        colors = CardDefaults.cardColors(
            containerColor = if (isNeuroSky) TechBlue.copy(alpha = 0.1f) else TechBackground
        ),
        border = BorderStroke(
            width = 1.dp,
            color = if (isNeuroSky) TechBlue else TechBorder
        )
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = try {
                        device.name ?: "未知设备"
                    } catch (e: SecurityException) {
                        "未知设备"
                    },
                    style = MaterialTheme.typography.bodyLarge,
                    color = if (isNeuroSky) TechBlue else TechTextPrimary,
                    fontWeight = if (isNeuroSky) FontWeight.Bold else FontWeight.Normal
                )
                
                Text(
                    text = device.address,
                    style = MaterialTheme.typography.bodySmall,
                    color = TechTextSecondary
                )
                
                if (isNeuroSky) {
                    Text(
                        text = "推荐设备",
                        style = MaterialTheme.typography.labelSmall,
                        color = TechBlue,
                        fontWeight = FontWeight.SemiBold
                    )
                }
            }
            
            Icon(
                imageVector = Icons.Default.Bluetooth,
                contentDescription = null,
                tint = if (isNeuroSky) TechBlue else TechTextSecondary,
                modifier = Modifier.size(24.dp)
            )
        }
    }
}